<template>
  <div v-infinite-scroll="load" infinite-scroll-distance="50" style="height: 100%">
    <OneContextMenu v-for="(email, emailIndex) in emailList" :key="emailIndex" :class="{'is_active': email.id === currentId}" class="msg-item hand" :items="contextMenuItems" :octm-data="email" @click="changeDetail(email)">
      <div class="first_name" :style="{ backgroundColor: generateEmailColor(email.fromEmailName) }">
        {{email.firstName}}
      </div>
      <div class="content">
        <div class="item">
          <div class="title ellipsis">
            <span v-if="!email.isSeen" class="status"></span>
            <span v-if="email.fromEmailName">
              {{ email.fromEmailName }}
            </span>
            <span v-if="email.toEmailName">、</span>
            <span v-if="email.toEmailName">{{ email.toEmailName }}</span>
          </div>
          <i class="iconfont icon-star star" @click="changeStatus(email)" v-if="email.isFlag" />
          <i class="iconfont icon-star unstar" @click="changeStatus(email)" v-else />
        </div>
        <div class="item">
          <div class="ellipsis">
            {{ email.subject }}
          </div>
          <div>
            <span class="group_num" v-if="email.groupNum && email.groupNum !== 1">{{ email.groupNum }}</span>
            <i class="iconfont icon-file" v-if="email.annexNum" />
          </div>
        </div>
        <div class="body">
          <div class="ellipsis flex-auto" v-html="email.bodyText"></div>
          <div class="ml5">{{ formateTime(email.receivedDate) }}</div>
        </div>
      </div>
    </OneContextMenu>
  </div>
</template>
  
<script lang="ts" setup>

import { defineProps, ref, onMounted, watch, defineEmits } from 'vue';
import dayjs from 'dayjs';
import { ElMessage } from 'element-plus';
import { storeToRefs } from 'pinia';
import { generateEmailColor } from '/@/utils/colorGenerator';


import api from "/@/api/email/index";
import { charToDarkColor, isCurrentYear } from '/@/utils';
import { useEmail } from '/@/stores/email';
import pinia from '/@/stores/index';
import { useRoute } from 'vue-router';
import OneContextMenu from '/@/components/Common/OneContextMenu.vue';
import { emit as emitEvent } from '@tauri-apps/api/event';

const props = defineProps({
  searchList: {
    type: Object,
    default: null,
  },
  refreshKey: {
    type: String,
    default: ''
  },
  filterParams: {
    type: Object,
    default: null,
  },
  currentMessageId: {
    type: [String, Number],
    default: ''
  },
});


const emit = defineEmits([ 'refresh', 'isReadyUpdateFolderNum', 'setUserBG' ]);
const loading = ref(false);
const route = useRoute();

const stores = useEmail(pinia);
const { currentId, curAccount, curFolder } = storeToRefs(stores);

const emailList = ref<any>([]);
const pageParams = ref<any>({
  page: 1,
  size: 15,
  total: 0
});

const contextMenuItems = ref([{
    id: 'unRead',
    label: '标记为未读',
    show: true,
    action: (obj: any) => {
      emitEvent('emial_operate', {
        operate: 'unRead',
        data: obj.octmData
      })
    }
  }, {
    id: 'moveTo',
    label: '移动到',
    show: true,
    action: (obj: any) => {
      emitEvent('emial_operate', {
        operate: 'moveTo',
        data: obj.octmData
      })
    }
  }, {
    id: 'reply',
    label: '回复',
    show: true,
    action: (obj: any) => {
      emitEvent('emial_operate', {
        operate: 'reply',
        data: obj.octmData
      })
    }
  }, {
    id: 'replyAll',
    label: '回复全部',
    show: true,
    action: (obj: any) => {
      emitEvent('emial_operate', {
        operate: 'replyAll',
        data: obj.octmData
      })
    }
  }, {
    id: 'forward',
    label: '转发',
    show: true,
    action: (obj: any) => {
      emitEvent('emial_operate', {
        operate: 'forward',
        data: obj.octmData
      })
    }
  }
])

const changeDetail = (item: any) => {
  // console.log('点击详情')
  // if (event) {
  //   event.stopPropagation();
  //   event.preventDefault();
  // }
  if (!item.isSeen) {
    // emit('refresh');
    // console.log("isReadyUpdateFolderNum")
    emit('isReadyUpdateFolderNum');
  }
  emit('refresh');
  emit('setUserBG', item.messageId, item.color);
  // item.isSeen = true;
  stores.setEmailId(item.id);
};

// 取消星标/设置为星标
const changeStatus  = (item: any) => {
  if (item.isFlag) {
    delStarTarget(item);
  } else {
    addStarTarget(item)
  }
  item.isFlag = !item.isFlag;
};

const delStarTarget = (item: any) => {
  api.email.delStarTarget({
    "account": item.account,
    "folderName": item.box,
    "messageId": item.messageId
  }).then(() => {
    ElMessage({ type: 'success', message: '操作成功' });
  })
};

const addStarTarget = (params: any) => {
  api.email.addStarTarget({
    "account": curAccount.value,
    "folderName": params.box,
    "messageId": params.messageId
  }).then(() => {
    ElMessage({ type: 'success', message: '操作成功' });
  });
};

const getEmailListBySearch =  async () => {
  if (loading.value) {
    return;
  }
  loading.value = true;
  const res = await api.email.searchMsg({
    account: curAccount.value,
    searchList: props.searchList,
    box: curFolder.value,
    pageNum: pageParams.value.page,
    pageSize: pageParams.value.size,
    ...props.filterParams
  });
  if(res.data.list.length) {
    const list = res.data.list.map((item: any) =>{
      let fromEmailName = item.fromEmailName;
      if (!fromEmailName) {
        fromEmailName = item.fromEmail?.slice(1, -1).split('@')[0];
      }

      let toEmailName = item.toEmailName;
      if (!toEmailName) {
        toEmailName = item.toEmail?.slice(0, -1).split('@')[0];
      }
      const firstName = fromEmailName.slice(0, 1);
      const color = charToDarkColor(firstName);
      return {
        ...item,
        fromEmailName,
        toEmailName,
        firstName,
        color,
        bodyText: item.bodyTextCut
      };
    });

    emailList.value = [...emailList.value, ...list];
  }
  pageParams.value.total = res.data.total;
  loading.value = false;
};

// 查询每个item的邮件数量
const getEmailListByDateType = async () => {
  if (loading.value) {
    return;
  }
  loading.value = true;
  const res = await api.email.getList({
    account: curAccount.value,
    folderName: curFolder.value,
    pageNum: pageParams.value.page,
    pageSize: pageParams.value.size,
    ...props.filterParams
  });
  if(res.data.length) {
    const list = res.data.map((item: any) =>{
      let fromEmailName = item.fromEmailName;
      if (!fromEmailName) {
        fromEmailName = item.fromEmail?.slice(1, -1).split('@')[0];
      }

      let toEmailName = item.toEmailName;
      if (!toEmailName) {
        toEmailName = item.toEmail?.slice(0, -1).split('@')[0];
      }
      const firstName = fromEmailName.slice(0, 1);
      const color = charToDarkColor(firstName);
      return {
        ...item,
        fromEmailName,
        toEmailName,
        firstName,
        color
      };
    });

    emailList.value = [...emailList.value, ...list];
  }
  pageParams.value.total = res.total;
  loading.value = false;
};

// 时间格式化
const formateTime = (time: string) => {
  if (!time) {
    return '';
  }
  return isCurrentYear(time) ? dayjs(time).format(('MM/DD')) : dayjs(time).format(('YYYY/MM/DD'))
};

// 滚动加载
const load = async () => {
  if (pageParams.value.total > emailList.value.length && !loading.value) {
    pageParams.value.page = pageParams.value.page + 1;
    if (props.searchList && props.searchList.length) {
      await getEmailListBySearch();
    } else {
      await getEmailListByDateType();
    }
  }
};

const refresh = () => {
  emailList.value.length = 0;
  pageParams.value.page = 1;
  if (props.searchList && props.searchList.length) {
    getEmailListBySearch();
  } else {
    getEmailListByDateType();
  }
};

const handlerToSwitchStatus = (status:string, messageId: string) => {
  console.log('handlerToSwitchStatus3', status, messageId) 
  console.log(emailList.value)
  // 根据id更新emailList
  // 快速找到对应的item
  const item = emailList.value.find((item: any) => item.topMessageId === messageId);
  console.log("快速找到对应的item:", item)
  if (item) {
    item.isSeen = false;
  }
};

// 根据邮箱生成颜色
// 发件人名称转换为数字哈希值，同一发件人每次都会得到相同的颜色
// const getEmailColor = (emailName: string) => {
//   const hash = emailName.charCodeAt(0) % 10;
//   const colors = ['#FF69B4', '#33CC33', '#6666CC', '#CC3333', '#CCCC33', '#33CCCC', '#CC66CC', '#CCCC66', '#666666', '#CCCCCC'];
//   return colors[hash];
// }

watch(() => props.refreshKey, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    refresh();
  }
});
watch(() => props.currentMessageId, (newVal, oldVal) => {
  // console.log('全部一度啦1:', newVal )
  // console.log('全部一度啦2:', emailList.value )
  // 根据currentMessageId更新emailList
  // 优化 快速找到对应的item
  const item = emailList.value.find((item: any) => item.topMessageId === newVal);
  if (item) {
    item.isSeen = true;
  }
})

onMounted(() => {
  if (!route.query.search) {
    refresh();
  }
});

defineExpose({ refresh, handlerToSwitchStatus });
  
</script>
<style lang="scss" scoped>
.msg-item {
  padding-left: 10px;
  padding-top: 12px;
  padding-bottom: 12px;
  position: relative;
  display: flex;

  &:hover {
    background: #eee;
    .unstar {
      display: inline-block;
    }
  }

  &.is_active {
    background: #3B7AEE;
    color: #fff;
    .content .body {
      color: #98BCFF;
    }

    .group_num {
      background-color: #98BCFF;
    }
  }

  .content {
    flex: 1;
    overflow: hidden;
    padding: 0 10px;
    line-height: 20px;
    font-size: 13px;
    .body {
      display: flex;
      color: #999;

      .ellipsis {
        height: 20px;
      }
    }
  }

  .star {
    color: #f73131;
  }

  .unstar {
    color: #cdcdcd;
    display: none;
  }
}

.status {
  width: 8px;
  height: 8px;
  background: #f73131;
  display: inline-block;
  border-radius: 50%;
  margin-right: 4px;
}

.icon-file {
  font-size: 12px;
  color: #fca146;
  margin-left: 5px;
}

.subject {
  margin-left: 2px;
}

.email_num {
  display: inline-block;
  border-radius: 7px;
  padding: 0 5px;
  height: 14px;
  background: #ccc;
  color: #666;
  text-align: center;
  margin-left: 5px;
}

.first_name {
  color: #fff;
  border-radius: 50%;
  height: 36px;
  width: 36px;
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  line-height: 36px;
  margin-top: 5px;
}

.item {
  display: flex;
  justify-content: space-between;
}

.title {
  font-size: 16px;
}

.group_num {
  background-color: #dfdfdf;
  border-radius: 8px;
  color: #fff;
  line-height: 17px;
  height: 17px;
  font-size: 12px;
  padding: 0 5px;
}
</style>  